﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

using WFL.Utils;

namespace WFL.Demo.WinForm
{
    public partial class OfficeForm : Form
    {
        public OfficeForm()
        {
            InitializeComponent();
        }

        private void _btnExcel_Click(object sender, EventArgs e)
        {

            #region 计算小鼠Excel

            ////计算小鼠Excel
            //string path = @"D:\Personal\Temp\mini\石化CRM期初数据准备模板8.xls";
            //ExcelApplication application = new ExcelApplication();
            //ExcelWorkbook book = null;
            //try
            //{
            //    book = application.Workbooks.Add(path);
            //    Dictionary<string, int> buffer = new Dictionary<string, int>(3500);
            //    using (ExcelWorksheet sheet = (ExcelWorksheet)book.Sheets[1])
            //    {
            //        int index = 2;
            //        while (true)
            //        {
            //            object codeObj = sheet.Range["A" + index.ToString()].GetValue();
            //            if (codeObj == null)
            //            {
            //                break;
            //            }
            //            string code = codeObj.ToString().Trim();
            //            Match match = Regex.Match(code, @"^0+");
            //            if (match.Success)
            //            {
            //                string code1 = code.Substring(match.Length);
            //                if (buffer.ContainsKey(code1))
            //                {
            //                    MessageBox.Show(index.ToString() + " " + code);
            //                }
            //            }
            //            if (!buffer.ContainsKey(code))
            //            {
            //                buffer.Add(code, 0);
            //            }
            //            buffer[code]++;
            //            index++;
            //        }
            //        MessageBox.Show(buffer.Count.ToString());
            //    }
            //    book.Close();
            //}
            //finally
            //{
            //    if (book != null)
            //    {
            //        book.Dispose();
            //    }
            //    application.Dispose();
            //}

            #endregion


            //ExcelApplication application = new ExcelApplication();
            //ExcelWorkbook book = null;
            //ExcelWorksheet sheet = null;
            //try
            //{
            //    book = application.Workbooks.Add();
            //    sheet = (ExcelWorksheet)book.Sheets.Add();

            //    sheet.Range[new int[] { 1, 28 }, new int[] { 1, 28 }].SetValue("28格");

            //    sheet.Cells.HAlign = HAlign.xlHAlignCenter;
            //    sheet.Cells.WrapText = true;
            //    sheet.Cells.RowHeight = 40;
            //    sheet.Cells.Font.Size = 14;
            //    sheet.Cells.Font.Bold = true;
            //    sheet.Cells.SetValue(2, 1, "我\n靠");
            //    //sheet.Cells.SetValue("B5", "A3", "你太粗鲁了");
            //    sheet.Cells.SetValue(1, 4, "神啊");

            //    ExcelRange range = sheet.Range["C11", "F16"];
            //    //range.Borders[BordersIndex.xlInsideHorizontal].LineStyle = WFL.Office.Excel.LineStyle.xlContinuous;
            //    //range.Borders[BordersIndex.xlInsideVertical].LineStyle = WFL.Office.Excel.LineStyle.xlContinuous;
            //    //以range左上角为1，1
            //    range.SetValue(-2, 0, "2013-07-25");
            //    range.SetValue(1, 1, "左上角,很长很长的内容，你看不到我了吧");
            //    object obj = range.Columns.AutoFit();
            //    range.SetValue("130101010001");
            //    object[,] value1 = (object[,])range.GetValue();

            //    range = sheet.Range["D12", "E13"];
            //    range.Merge(false);

            //    range = sheet.Range["C17", "F22"];
            //    string[,] values = new string[6, 4];
            //    for (int i = 0; i < values.GetLength(0); i++)
            //    {
            //        for (int j = 0; j < values.GetLength(1); j++)
            //        {
            //            values[i, j] = i.ToString() + j.ToString();
            //        }
            //    }
            //    //range.SetValue(values);
            //    range.SetValue(new string[2, 2] { { "qq", "nn" }, { "tt", "yy" } });

            //    object value = range.GetValue("B30");

            //    object[,] value2 = (object[,])range.GetValue();

            //    range.Borders[BordersIndex.xlInsideHorizontal].LineStyle = Excel.LineStyle.xlDouble;

            //    range = null;

            //    sheet.Columns[4].Delete(DeleteShiftDirection.xlShiftToLeft);

            //    book.Sheets[2].Select();

            //    book.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "automatic.xls");
            //    //book.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "automatic.xlsx");

            //    book.Close();
            //}
            //finally
            //{
            //    sheet.Dispose();
            //    book.Dispose();
            //    application.Dispose();
            //}
        }

        private void _btnWord_Click(object sender, EventArgs e)
        {
            //WordApplication word = new WordApplication();
            //WordDocument document = null;
            //try
            //{
            //    document = word.Documents.Add();
            //    WordParagraph paragraph = document.Paragraphs.Add();
            //    WordRange range = paragraph.Range;
            //    range.Text = "测试数据啦测试数据啦测试数据啦测试数据啦测试数据啦测试数据啦测试数据啦测试数据啦测试数据啦";

            //    paragraph = document.Paragraphs.Add();
            //    range = paragraph.Range;
            //    range.Text = "另一个段落另一个段落";
            //    range.InsertBefore("这是段落开头");
            //    range.InsertAfter("--这是小尾巴");
            //    //添加表格后，段落的文字被全部覆盖
            //    WordTable table = range.Tables.Add(range, 5, 6);
            //    table.Borders.InsideLineStyle = Word.LineStyle.wdLineStyleSingle;
            //    table.Borders.OutsideLineStyle = Word.LineStyle.wdLineStyleSingle;
            //    range.InsertBefore("此时的努力开始");
            //    range.InsertAfter("--尝试插入小尾巴");
            //    //设置尾巴样式
            //    range.SetRange(range.End - 9, range.End);
            //    //range.Style = document.Styles["标题 1"];
            //    //range.Style = document.Styles[1];

            //    //foreach (WordStyle style in document.Styles)
            //    //{
            //    //    MessageBox.Show(style.NameLocal);
            //    //}

            //    range = paragraph.Range;
            //    range.InsertBefore("努力开始");
            //    range.SetRange(range.Start + 4, range.End);
            //    range.Font.Bold = true;
            //    paragraph = document.Paragraphs.Add();
            //    range = paragraph.Range;
            //    range.SetStyle(BuiltinStyle.wdStyleNormal);
            //    table = range.Tables.Add(range, 3, 4);

            //    //插入html测试
            //    if (!string.IsNullOrEmpty(_tbHtml.Text))
            //    {
            //        _btnCopy_Click(null, null);
            //        //样式合并与否可控
            //        range.PasteAndFormat(RecoveryType.wdFormatOriginalFormatting);
            //    }
            //    ////文件方式插入Html，样式被合并
            //    //range.InsertFile(AppDomain.CurrentDomain.BaseDirectory + "test.html");

            //    //设置页码，并设置格式
            //    WordRange footer = document.Sections[1].Footers[HeaderFooterIndex.wdHeaderFooterPrimary].Range;
            //    footer.Font.Bold = true;
            //    footer.Font.Size = 14;
            //    footer.InsertAfter("第 ");
            //    footer.Collapse(CollapseDirection.wdCollapseEnd);
            //    footer.Fields.Add(footer, FieldType.wdFieldEmpty, "PAGE");
            //    footer.Expand(Units.wdParagraph);
            //    footer.InsertAfter(" 页 共 ");
            //    footer.Collapse(CollapseDirection.wdCollapseEnd);
            //    footer.Fields.Add(footer, FieldType.wdFieldEmpty, "NUMPAGES");
            //    footer.Expand(Units.wdParagraph);
            //    footer.InsertAfter(" 页");

            //    document.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "automatic.doc");
            //    document.Close();
            //}
            //finally
            //{
            //    word.Dispose();
            //    word = null;
            //}
        }

        private void _btnCopy_Click(object sender, EventArgs e)
        {
            string html = _tbHtml.Text;
            if (!string.IsNullOrEmpty(html))
            {
                DataObject dataObject = new DataObject();
                html = ClipboardFormatHelper.Html(html);
                ////把字符串用utf-8加密，该方法有问题
                //byte[] utf8Pre = Encoding.UTF8.GetPreamble();
                //byte[] defaultPre = Encoding.Default.GetPreamble();
                //byte[] bytes_utf8 = Encoding.UTF8.GetBytes(html);
                //byte[] bytes_default = Encoding.Default.GetBytes(html);
                //html = Encoding.Default.GetString(Encoding.UTF8.GetBytes(html));
                ////用Default解码后再编码回来，字节序列发生变化（为什么？）。
                //byte[] back = Encoding.Default.GetBytes(html);
                ////所以下面这句返回的字符串也以改变。
                //html = Encoding.UTF8.GetString(Encoding.Default.GetBytes(html));
                //dataObject.SetData(DataFormats.Html, html);
                //Clipboard.SetDataObject(dataObject);

                MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(html));
                try
                {
                    dataObject.SetData(DataFormats.Html, stream);
                    Clipboard.SetDataObject(dataObject, true);
                }
                finally
                {
                    stream.Close();
                }
            }
        }

        private void _btnClipboardFormat_Click(object sender, EventArgs e)
        {
            IDataObject dataObject = Clipboard.GetDataObject();

            //以下方式获取的DataFormats.Html格式的数据解码有误
            object data = dataObject.GetData(DataFormats.Html);
            string html = Encoding.UTF8.GetString(Encoding.Default.GetBytes(data.ToString()));

            //采用流的方式获取，自己解码（DataFormats.Html显示为“HTML Format”与下面的“Html Format”区别？）
            MemoryStream stream = dataObject.GetData("Html Format") as MemoryStream;
            try
            {
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, (int)stream.Length);
                string text = Encoding.UTF8.GetString(buffer);
            }
            finally
            {
                stream.Close();
            }

            string[] formats = dataObject.GetFormats(false);
            string tip = null;
            foreach (string format in formats)
            {
                tip += format + "\r\n";
            }
            MessageBox.Show(tip);
        }

        private void _btnHtmlOffset_Click(object sender, EventArgs e)
        {
            string html = "Version:0.9\r\nStartHTML:0000000138\r\nEndHTML:0000001516\r\nStartFragment:0000000174\r\nEndFragment:0000001480\r\nSourceURL:http://www.baidu.com/\r\n<html>\r\n<body>\r\n<!--StartFragment--><a href=\"http://tieba.baidu.com/\" name=\"tj_tieba\" style=\"color: rgb(0, 0, 204); font-size: 14px; font-family: arial; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: auto; text-align: left; text-indent: 137px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255);\">贴 吧</a><span style=\"color: rgb(0, 0, 0); font-family: arial; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: auto; text-align: left; text-indent: 137px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); display: inline !important; float: none;\">　</span><a href=\"http://zhidao.baidu.com/\" name=\"tj_zhidao\" style=\"color: rgb(0, 0, 204); font-size: 14px; font-family: arial; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: auto; text-align: left; text-indent: 137px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255);\">知 道</a><!--EndFragment-->\r\n</body>\r\n</html>";
            int endHTML = Encoding.UTF8.GetByteCount(html);
            html = "Version:0.9\r\nStartHTML:0000000138\r\nEndHTML:0000001516\r\nStartFragment:0000000174\r\nEndFragment:0000001480\r\nSourceURL:http://www.baidu.com/\r\n";
            int startHTML = Encoding.UTF8.GetByteCount(html);
            html = "Version:0.9\r\nStartHTML:0000000138\r\nEndHTML:0000001516\r\nStartFragment:0000000174\r\nEndFragment:0000001480\r\nSourceURL:http://www.baidu.com/\r\n<html>\r\n<body>\r\n<!--StartFragment-->";
            int startFragment = Encoding.UTF8.GetByteCount(html);
            html = "Version:0.9\r\nStartHTML:0000000138\r\nEndHTML:0000001516\r\nStartFragment:0000000174\r\nEndFragment:0000001480\r\nSourceURL:http://www.baidu.com/\r\n<html>\r\n<body>\r\n<!--StartFragment--><a href=\"http://tieba.baidu.com/\" name=\"tj_tieba\" style=\"color: rgb(0, 0, 204); font-size: 14px; font-family: arial; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: auto; text-align: left; text-indent: 137px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255);\">贴 吧</a><span style=\"color: rgb(0, 0, 0); font-family: arial; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: auto; text-align: left; text-indent: 137px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); display: inline !important; float: none;\">　</span><a href=\"http://zhidao.baidu.com/\" name=\"tj_zhidao\" style=\"color: rgb(0, 0, 204); font-size: 14px; font-family: arial; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: auto; text-align: left; text-indent: 137px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255);\">知 道</a>";
            int endFragment = Encoding.UTF8.GetByteCount(html);

            //默认数据设置
            html = "Version:0.9\r\nStartHTML:0000000138\r\nEndHTML:0000001516\r\nStartFragment:0000000174\r\nEndFragment:0000001480\r\n";
            int defaultStartHtml = Encoding.UTF8.GetByteCount(html);
            html = "Version:0.9\r\nStartHTML:0000000138\r\nEndHTML:0000001516\r\nStartFragment:0000000174\r\nEndFragment:0000001480\r\n<html>\r\n<body>\r\n<!--StartFragment-->";
            int defaultstartFragment = Encoding.UTF8.GetByteCount(html);
            //默认尾部长度
            html = "<!--EndFragment-->\r\n</body>\r\n</html>";
            int defaultEndFragmentOffset = Encoding.UTF8.GetByteCount(html);

            
        }
    }
}
